package cn.imokay.juc.threadshutdown;

import java.util.concurrent.TimeUnit;

public class InterrupteDemo {
    public static void main(String[] args) {
        //demo1();

        demo2();




    }

    private static void demo2() {
        Thread t1 = new Thread(()->{
            while (true) {
                if (Thread.currentThread().isInterrupted()) {
                    System.out.println("线程中断状态："+Thread.currentThread().isInterrupted());
                    System.out.println("线程被中断，现在立即退出");
                    break;
                }

                if (Thread.interrupted()) {//该静态方法会重置状态为false
                    System.out.println("线程中断状态："+Thread.currentThread().isInterrupted());
                    System.out.println("线程被中断，现在立即退出");
                    break;
                }

                try {
                    System.out.println("睡200毫秒");
                    Thread.sleep(200);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                    //throw new RuntimeException(e);
                    Thread.currentThread().interrupt();
                }
            }

        },"t1");
        t1.start();

        t1.interrupted();

        try { TimeUnit.SECONDS.sleep(1); } catch (Exception e) { e.printStackTrace();}

        new Thread(()->{
            System.out.println("t1被t2interrupt");
                 t1.interrupt();
        },"t2").start();
    }

    private static void demo1() {
        Thread t1 = new Thread(() -> {

                while (true) {
                    if (Thread.currentThread().isInterrupted()) {
                        System.out.println(Thread.currentThread().getName() + "\t---isInterrupted为ture,被协商终止---");
                        break;
                    }
                    System.out.println(Thread.currentThread().getName() + "\t---hello,isInterrupted---");
                }


        }, "t1");

        t1.start();

        try { TimeUnit.SECONDS.sleep(1); } catch (Exception e) { e.printStackTrace();}

        t1.interrupt();
        System.out.println(t1.isInterrupted());


        try { TimeUnit.SECONDS.sleep(1); } catch (Exception e) { e.printStackTrace();}

        //未活动的线程，未fasle，此时没有意义
        System.out.println(t1.isInterrupted());
    }
}
